import React, { useEffect, useMemo, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import orgService from '@/api/services/orgService';
import { DatasetSearchModeEnum, GetDatasetList } from '@/common';
import SelectDatasetCascader from '@/components/dataset/SelectDatasetCascader';
import { SelectedDatasetType } from '@/types/app/type';

import { WorkflowContext } from '../../../../../context';

import type { RenderInputProps } from '../type';

const SelectDatasetRender = ({ inputs = [], item, nodeId }: RenderInputProps) => {
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);
  const app_id = useContextSelector(WorkflowContext, (v) => v.appId);

  const [data, setData] = useState({
    searchMode: DatasetSearchModeEnum.embedding,
    limit: 5,
    similarity: 0.5,
    usingReRank: false,
  });

  const [datasetList, setDatasetList] = useState<GetDatasetList[]>([]);

  const [isOpenDatasetSelect, setIsOpenDatasetSelect] = useState(false);

  const onOpenDatasetSelect = () => setIsOpenDatasetSelect(true);
  const onCloseDatasetSelect = () => setIsOpenDatasetSelect(false);

  const selectedDatasetsValue = useMemo(() => {
    if (Array.isArray(item.value)) return item.value as SelectedDatasetType;
    return [] as SelectedDatasetType;
  }, [item.value]);

  const initDatasetList = async () => {
    const res = await orgService.getDataset({ appId: app_id });
    setDatasetList(res.list);
  };

  useEffect(() => {
    initDatasetList();
  }, []);

  useEffect(() => {
    inputs.forEach((input) => {
      // @ts-ignore
      if (data[input.key] !== undefined) {
        setData((state) => ({
          ...state,
          [input.key]: input.value,
        }));
      }
    });
  }, [data, inputs]);

  const Render = useMemo(() => {
    return (
      <div
        className="w-full min-w-[350px] grid-cols-2 gap-4"
        // gridTemplateColumns={'repeat(2, minmax(0, 1fr))'}
        // gridGap={4}
        // minW={'350px'}
        // w={'100%'}
      >
        <SelectDatasetCascader
          selectedDatasets={selectedDatasetsValue}
          datasets={datasetList}
          onChange={(e) => {
            onChangeNode({
              nodeId,
              key: item.key,
              type: 'updateInput',
              value: {
                ...item,
                value: e,
              },
            });
          }}
        />
      </div>
    );
  }, [item, nodeId, onChangeNode, selectedDatasetsValue, datasetList]);

  return Render;
};

export default React.memo(SelectDatasetRender);
